<template>
  <div class="wish-list-container">
    <el-card>
      <div slot="header" class="header">
        <span>心愿目标</span>
        <el-button type="primary" @click="handleAdd">新增心愿</el-button>
      </div>

      <el-row :gutter="20">
        <el-col :span="8" v-for="wish in wishList" :key="wish.id">
          <el-card class="wish-card" :body-style="{ padding: '0px' }">
            <div class="wish-header">
              <span class="wish-title">{{ wish.title }}</span>
              <el-tag :type="wish.status === '已完成' ? 'success' : 'warning'">
                {{ wish.status }}
              </el-tag>
            </div>
            <div class="wish-content">
              <div class="wish-info">
                <p class="wish-desc">{{ wish.description }}</p>
                <div class="wish-progress">
                  <span>目标金额：¥{{ wish.targetAmount }}</span>
                  <span>已存金额：¥{{ wish.savedAmount }}</span>
                </div>
                <el-progress 
                  :percentage="Number(((wish.savedAmount / wish.targetAmount) * 100).toFixed(1))"
                  :color="wish.status === '已完成' ? '#67C23A' : '#409EFF'">
                </el-progress>
              </div>
            </div>
            <div class="wish-footer">
              <el-button type="text" @click="handleEdit(wish)">编辑</el-button>
              <el-button type="text" @click="handleAddAmount(wish)">存入</el-button>
              <el-button type="text" class="delete-btn" @click="handleDelete(wish)">删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="wishForm" :rules="rules" ref="wishForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="wishForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="wishForm.description"></el-input>
        </el-form-item>
        <el-form-item label="目标金额" prop="targetAmount">
          <el-input-number v-model="wishForm.targetAmount" :precision="2" :step="100" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="已存金额" prop="savedAmount">
          <el-input-number v-model="wishForm.savedAmount" :precision="2" :step="100" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="wishForm.status" placeholder="请选择状态">
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 存入金额对话框 -->
    <el-dialog title="存入金额" :visible.sync="amountDialogVisible" width="400px">
      <el-form :model="amountForm" :rules="amountRules" ref="amountForm" label-width="100px">
        <el-form-item label="存入金额" prop="amount">
          <el-input-number v-model="amountForm.amount" :precision="2" :step="100" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="amountDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAmount">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WishList',
  data() {
    return {
      wishList: [],
      dialogVisible: false,
      amountDialogVisible: false,
      dialogTitle: '新增心愿',
      currentWish: null,
      wishForm: {
        title: '',
        description: '',
        targetAmount: 0,
        savedAmount: 0,
        status: '进行中'
      },
      amountForm: {
        amount: 0
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        targetAmount: [
          { required: true, message: '请输入目标金额', trigger: 'blur' }
        ],
        savedAmount: [
          { required: true, message: '请输入已存金额', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      amountRules: {
        amount: [
          { required: true, message: '请输入存入金额', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchWishList()
  },
  methods: {
    async fetchWishList() {
      try {
        const response = await this.$http.get('/goal/list')
        if (response.data.code === 20000) {
          this.wishList = response.data.data.rows || []
        } else {
          throw new Error(response.data.message || '获取心愿列表失败')
        }
      } catch (error) {
        console.error('Fetch wish list error:', error)
        this.$message.error('获取心愿列表失败')
      }
    },
    handleAdd() {
      this.dialogTitle = '新增心愿'
      this.wishForm = {
        title: '',
        description: '',
        targetAmount: 0,
        savedAmount: 0,
        status: '进行中'
      }
      this.dialogVisible = true
    },
    handleEdit(wish) {
      this.dialogTitle = '编辑心愿'
      this.wishForm = { ...wish }
      this.dialogVisible = true
    },
    handleAddAmount(wish) {
      this.currentWish = wish
      this.amountForm.amount = 0
      this.amountDialogVisible = true
    },
    async handleDelete(wish) {
      try {
        await this.$confirm('确认删除该心愿吗？', '提示', {
          type: 'warning'
        })
        const response = await this.$http.delete(`/goal/${wish.id}`)
        if (response.data.code === 20000) {
          this.$message.success('删除成功')
          this.fetchWishList()
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Delete wish error:', error)
          this.$message.error('删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.wishForm.validate(async valid => {
        if (valid) {
          try {
            let response
            const wishData = {
              title: this.wishForm.title,
              description: this.wishForm.description,
              targetAmount: this.wishForm.targetAmount,
              savedAmount: this.wishForm.savedAmount,
              status: this.wishForm.status
            }

            if (this.wishForm.id) {
              response = await this.$http.put('/goal', {
                ...wishData,
                id: this.wishForm.id
              })
            } else {
              response = await this.$http.post('/goal', wishData)
            }

            if (response.data.code === 20000) {
              this.$message.success('保存成功')
              this.dialogVisible = false
              this.fetchWishList()
            } else {
              throw new Error(response.data.message || '保存失败')
            }
          } catch (error) {
            console.error('Save wish error:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    submitAmount() {
      this.$refs.amountForm.validate(async valid => {
        if (valid) {
          try {
            const newAmount = this.currentWish.savedAmount + this.amountForm.amount
            await this.$http.put(`/goal`, {
              ...this.currentWish,
              savedAmount: newAmount,
              status: newAmount >= this.currentWish.targetAmount ? '已完成' : '进行中'
            })
            this.$message.success('存入成功')
            this.amountDialogVisible = false
            this.fetchWishList()
          } catch (error) {
            this.$message.error('存入失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.wish-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wish-card {
  margin-bottom: 20px;
}

.wish-header {
  padding: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}

.wish-title {
  font-size: 16px;
  font-weight: bold;
}

.wish-content {
  padding: 14px;
}

.wish-desc {
  margin-bottom: 10px;
  color: #606266;
}

.wish-progress {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.wish-footer {
  padding: 14px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #F56C6C;
}
</style> 